package com.example.bletestutils;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleReadCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.example.bletestutils.databinding.ActivityControlBinding;
import com.example.bletestutils.databinding.ActivityControlNewBinding;
import com.example.bletestutils.utils.FastBleUtils;
import com.example.bletestutils.utils.MyUtils;
import com.example.bletestutils.utils.SpUtil;
import com.example.bletestutils.view.DownOrUpListener;
import com.example.bletestutils.view.KnobView;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;

public class ControlActivityNew extends BaseActivity implements View.OnClickListener, DownOrUpListener {
    private com.example.bletestutils.databinding.ActivityControlNewBinding inflate;
    private BleDevice dev;
    private BleDevice currentBleDev;

    private UUID SERVICE_UUUID = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
    private UUID SERVICEF000_UUUID = UUID.fromString("0000f000-0000-1000-8000-00805f9b34fb");
    private UUID WRITE_UUUID = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
    private UUID NOTIFY_UUUID = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");
    private UUID F001_UUUID = UUID.fromString("0000f001-0000-1000-8000-00805f9b34fb");
    private UUID F002_UUUID = UUID.fromString("0000f002-0000-1000-8000-00805f9b34fb");

    private long time;
    long sendSize = 0;
    long receviceSize = 0;

    Handler nH = new Handler();
    Handler hConnect = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflate = ActivityControlNewBinding.inflate(getLayoutInflater());
        setContentView(inflate.getRoot());
        getIntentData();

        initView();

        LiveEventBus.get("DIS_BLE", String.class).observe(this, mac -> {
            BleManager.getInstance().disconnectAllDevice();
            SpUtil.clear();
            inflate.tvDeviceName.setText("未连接");
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        final String mac = SpUtil.getString("mac");
        if (TextUtils.isEmpty(mac)) {
            inflate.tvDeviceName.setText("未连接");
        } else {
            if (BleManager.getInstance().isConnected(mac)) {
                List<BleDevice> allConnectedDevice = BleManager.getInstance().getAllConnectedDevice();
                for (BleDevice bleDevice : allConnectedDevice) {
                    if (bleDevice.getMac().equals(mac)) {
                        currentBleDev = bleDevice;
                        inflate.tvDeviceName.setText(currentBleDev.getName());
                        break;
                    }
                }
            } else {
                inflate.tvDeviceName.setText("未连接");
                //TODO 是否自动连接
                FastBleUtils.getInstant().connectBle(mac, callback);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (currentBleDev != null) {
            FastBleUtils.getInstant().bleDisConnect(currentBleDev);
        }
        hConnect.removeCallbacksAndMessages(null);
    }

    private void initView() {

        inflate.btnBluetooth.setOnClickListener(this);

        inflate.rg.setOnCheckedChangeListener((radioGroup, i) -> {
            if (i == R.id.rb_1) {
                inflate.ll0.setVisibility(View.VISIBLE);
                inflate.ll1.setVisibility(View.GONE);
            } else {
                inflate.ll0.setVisibility(View.GONE);
                inflate.ll1.setVisibility(View.VISIBLE);
            }
        });

        //旋钮
        inflate.controlView.setListener(new KnobView.OnResultListener() {
            @Override
            public void onChangedValue(float value) {
                Log.e(TAG, "100毫秒内变化的角度：$value");
                //没有转动就跳过
                if (value == 0) return;
                byte[] msg = intToByteArr((int) value);
                //02是转纽的id 00 1F是角度 0d 0a是数据尾，说明数据完结
                // 创建一个新的数组，长度为原始数组长度+3（前边1个，末尾2个）
                byte[] newMsg = new byte[msg.length + 3];

                // 将0x00追加到新数组的前边
                newMsg[0] = 0x02;
                // 将原始数组的内容复制到新数组中
                System.arraycopy(msg, 0, newMsg, 1, msg.length);

                // 将0x0d和0x0a追加到新数组的末尾
                newMsg[msg.length + 1] = 0x0d;
                newMsg[msg.length + 2] = 0x0a;
                writeData(newMsg);
            }

            @Override
            public void onFinalValue(float finalValue) {
                Log.e(TAG, "   ===最终变化的角度：" + finalValue);
            }
        });

        //按键
        inflate.tvMute.setListener(this);
        inflate.tvInput.setListener(this);
        inflate.tvSuggestedSetting.setListener(this);
        inflate.tvReset.setListener(this);
        inflate.tvSettingDefault.setListener(this);

        inflate.btnFanxiang.setListener(this);
        inflate.tvL.setListener(this);
        inflate.tvR.setListener(this);
        inflate.tvMode1.setListener(this);
        inflate.tvMode2.setListener(this);
        inflate.tvMode3.setListener(this);
        inflate.tvMode4.setListener(this);

        inflate.tvGyzyAdd.setListener(this);
        inflate.tvGyzySub.setListener(this);

        inflate.tvDyzyAdd.setListener(this);
        inflate.tvDyzySub.setListener(this);

        inflate.tvZyzyAdd.setListener(this);
        inflate.tvZyzySub.setListener(this);

        inflate.tvCdyzyAdd.setListener(this);
        inflate.tvCdyzySub.setListener(this);
        inflate.btnGyyc.setListener(this);

    }

    /**
     * 旋钮角度转换为发送的数据
     */
    public byte[] intToByteArr(int intVal) {

        int i;
        if (intVal < 0) {
            i = 0x28000 - intVal;
        } else {
            i = 0x20000 + intVal;
        }

        String a = Integer.toHexString(i);
        String b = (a.length() % 2 == 1) ? "0" + a : a;

        // 在 Java 中没有直接的 chunked 方法，我们需要自己实现这个功能
        List<String> chunks = new ArrayList<>();
        for (int j = 0; j < b.length(); j += 2) {
            chunks.add(b.substring(j, Math.min(j + 2, b.length())));
        }

        List<Integer> list = new ArrayList<>();
        for (String chunk : chunks) {
            list.add(Integer.parseInt(chunk, 16));
        }

        byte[] msg = new byte[list.size()];
        for (int k = 0; k < list.size(); k++) {
            msg[k] = list.get(k).byteValue();
        }

        return msg;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_bluetooth:
                startActivity(new Intent(this, MainActivity.class));
                break;
        }
    }

    private void getIntentData() {
        Intent intent = getIntent();
        dev = intent.getParcelableExtra("dev");
        if (dev == null) {
            toastText("无法获取蓝牙参数");
//            finish();
        }
        bleConnect(dev, 0);

    }

    private void bleConnect(BleDevice bleDevice, long delay) {

        Log.e(TAG, "bleConnect: " + (bleDevice == null));
        hConnect.removeCallbacksAndMessages(null);
        hConnect.postDelayed(new Runnable() {
            @Override
            public void run() {
                //说明是我们的产品，风扇具体看实际
                FastBleUtils.getInstant().connectBle(bleDevice, callback);
            }
        }, delay);

    }

    private BleGattCallback callback = new BleGattCallback() {
        @Override
        public void onStartConnect() {
            Log.e(TAG, "onStartConnect: ");
        }

        @Override
        public void onConnectFail(BleDevice bleDevice, BleException exception) {
            Log.e(TAG, "onConnectFail: " + exception);
            toastText("链接失败");

        }

        @SuppressLint("MissingPermission")
        @Override
        public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
            Log.e(TAG, "onConnectSuccess:");
            if (status != BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "onConnectSuccess:bleDis Connect ");
                FastBleUtils.getInstant().bleDisConnect(bleDevice);
                return;
            }
            currentBleDev = bleDevice;
            List<BluetoothGattService> services = gatt.getServices();
            if (services.isEmpty()) {
                Log.e(TAG, "onConnectSuccess: 服务特征为空！");
            } else {
                services.forEach(new Consumer<BluetoothGattService>() {
                    @Override
                    public void accept(BluetoothGattService bluetoothGattService) {

                        List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
                        Log.e(TAG, "accept:ServiceUUID: " + bluetoothGattService.getUuid().toString());
                        if (characteristics != null)
                            characteristics.forEach(new Consumer<BluetoothGattCharacteristic>() {
                                @Override
                                public void accept(BluetoothGattCharacteristic bluetoothGattCharacteristic) {
                                    Log.e(TAG, "accept:getUuid " + bluetoothGattCharacteristic.getUuid());
                                }
                            });
                    }
                });
            }
            toastText("连接成功");

            openNotify(bleDevice, 100);
//                        setmtu(200);

            //TODO
            // 用于判断APP已经连上蓝牙MCU，mcu发数据过去同步APP列表
            inflate.tvDeviceName.setText(bleDevice.getName());

            writeData(new byte[]{0x01, 0x09});
            SpUtil.put("mac", currentBleDev.getMac());


        }

        @Override
        public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
            try {
                toastText("断开连接。");
                inflate.tvDeviceName.setText("断开连接");
                Log.e(TAG, "onDisConnected: ");
            } catch (Exception e) {
                Log.e(TAG, "onDisConnected: " + e);
            }
        }
    };

    public void writeData(byte[] data) {
        if (currentBleDev == null) {
//            toastText("设备未连接");
            return;
        }
        FastBleUtils.getInstant().writeBleData(currentBleDev, SERVICE_UUUID.toString(), WRITE_UUUID.toString(), data, bleWriteCallback);
    }

    BleWriteCallback bleWriteCallback = new BleWriteCallback() {
        @Override
        public void onWriteSuccess(int current, int total, byte[] justWrite) {
            Log.e(TAG, "onWriteSuccess: " + new String(justWrite) + ";hexStr:" + HexUtil.formatHexString(justWrite));
//            logtv("Write:"+(inflate.cbCheckbox.isChecked()?HexUtil.formatHexString(justWrite):new Gson().toJson(justWrite)));
            if (justWrite != null)
                sendSize += justWrite.length;
            showSize();
        }

        @Override
        public void onWriteFailure(BleException exception) {
            toastText("onWriteFailure");
            Log.e(TAG, "onWriteFailure: " + exception);
        }
    };

    private void openNotify(BleDevice bleDevice, long delay) {
        nH.removeCallbacksAndMessages(null);
        Log.e(TAG, "openNotify: 开启通知:" + NOTIFY_UUUID.toString());
        nH.postDelayed(new Runnable() {
            @Override
            public void run() {
                FastBleUtils.getInstant().openNotify(bleDevice, SERVICE_UUUID.toString(), NOTIFY_UUUID.toString(), new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        logtv("onNotifySuccess: ");
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        logtv("onNotifyFailure: ");
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        logtv((HexUtil.formatHexString(data)));
                        if (data != null)
                            receviceSize += data.length;
                        showSize();
                        //TODO 接收数据
                        readData(data);
                    }
                });
            }
        }, delay);
    }

    /**
     * MCU-》app
     * <p>
     * 55 AA 04 05 01 88 48 41 44 0D 0A
     * 55 AA 01 20 58 4C 52 31 20 0D
     * 55 AA 03 05 00
     * 55 AA 02 20 20 20 20 20 20 20 20 20 20 0D 0A 20 20 20 20 20
     * 55 AA 02 20 20 20 20 20 20 20 20 20 20 0D 0A 20 20 20 20 20
     * <p>
     * 第一行的是更新下拉菜单的选项，
     * 第二行是屏幕第一行显示的内容。
     * 第三行是显示音量的数据，
     * 第四行是屏幕第二行的显示内容，
     * 55 aa是每行的开头，之后的一个数据就是数据的id,再之后就是它的内容
     * 55 AA 03 20 20 20 20 20 20 20 20 20 20 0D 0A 20 20 20 20 20
     * 多加一行显示数据，之前4.2只有两行显示，不够用，多加一行
     *
     * @param dataArray
     */
    private void readData(byte[] dataArray) {
        try {

            // 拆分字节数组
            List<byte[]> splitArrays = MyUtils.splitByteArrayBySequence(dataArray, new byte[]{(byte) 0x0D, (byte) 0x0A});
            for (byte[] data : splitArrays) {
                if (data.length < 3) return;
                byte id = data[2];
                if (id == 0x01) {//第一行
                    inflate.tvLine1.setText(getNewByteArrayText(data, 3).replaceFirst("  ", ""));
                } else if (id == 0x02) {//第2行
                    inflate.tvLine2.setText(getNewByteArrayText(data, 3).replaceFirst("  ", ""));
                } else if (id == 0x03) {//第3行
                    // 从 data 的第四个元素（索引为 3）获取音量值，并将其转换为字符串
                    int volume = data[3] & 0xFF; // 需要将 byte 转换为无符号的 int，因此使用 & 0xFF
                    String volumeStr = Integer.toString(volume);
                    Log.e(TAG, volumeStr); // 在日志中打印音量值
                    inflate.tvVolume.setText(volumeStr); // 将音量值设置为 TextView 的文本
                    // 调用 setVolumeProgress 方法，并传入音量值（已经是 int 类型，无需再次转换）
                    setVolumeProgress(volume);

                    // 从 data 的第五个元素（索引为 4）获取字节，并检查 bit7
                    int bit = (data[4] & 0xFF) >> 7 & 1; // 右移 7 位，然后与 1 进行与运算以获取 bit7 的值
                    if (bit == 1) {
//                    dropDownSend(); // 如果 bit7 为 1，则调用 dropDownSend 方法
                    }

                    //bit6:  0，正常 1：相当于按下APP的（Disconnect Bluetooth）
                    int bit6 = (data[4] & 0xFF) >> 6 & 1; // 右移 6 位，然后与 1 进行与运算以获取 bit6 的值
                    if (bit6 == 1) {
                        //TODO 断开蓝牙，并清理缓存
                    }

                } else if (id == 0x05) {//第4行 第3行文字
                    inflate.tvLine3.setText(getNewByteArrayText(data, 3).replaceFirst("  ", ""));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理接收的数据
     */
    private String getNewByteArrayText(byte[] src, int start) {
        int length = src.length - start;
        byte[] temp = new byte[length];

        for (int index = start; index < src.length; index++) {
            byte b = src[index];
            // 忽略换行符（0x0A 和 0x0D）的逻辑在 Kotlin 版本中是空的，所以这里也保持为空
            // 但注意：根据你的需求，你可能想在这里添加一些逻辑来处理换行符

            // 将从 start 位置开始的数据复制到 temp 数组中
            temp[index - start] = b;
        }

        // 注意：这里的逻辑没有去掉末尾的 2 个换行符，因为 Kotlin 版本也没有这个逻辑
        // 如果你需要去掉末尾的换行符，你需要在复制完成后添加额外的逻辑来处理

        return new String(temp, StandardCharsets.UTF_8);
    }

    /**
     * 设置音量
     *
     * @param value
     */
    private void setVolumeProgress(int value) {
        // 假设最大音量为60，音量格子数为9，计算进度索引
        int index = getVolumeIndex(value); // 假设这个方法已经在Java代码中定义

        LinearLayout ll_v = findViewById(R.id.ll_v); // 假设ll_v是已经在布局文件中定义的LinearLayout，并且这里通过findViewById获取到了它的实例

        for (int i = 0; i < ll_v.getChildCount(); i++) {
            // 获取子控件
            View childView = ll_v.getChildAt(ll_v.getChildCount() - 1 - i); // 由于是从后往前遍历，所以使用ll_v.getChildCount() - 1 - i来获取正确的索引
            if (childView instanceof ImageView) {
                ImageView imageView = (ImageView) childView;
                Drawable drawable = imageView.getDrawable();

                if (i <= index) {
                    drawable.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY));
                } else {
                    drawable.setColorFilter(new PorterDuffColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY));
                }

                imageView.setImageDrawable(drawable); // 在某些情况下，这一步可能是不必要的，因为setColorFilter已经改变了drawable的显示。但是，为了确保更改生效，这里还是保留了setImageDrawable调用。
            }
        }
    }

    public int getVolumeIndex(int currentVolume) {
        // 音量段的范围（每个段大约7个单位），但这里我们除以8来确保覆盖到60
        int rangePerSegment = 60 / 8;
        if (rangePerSegment == 0) {
            // 防止除数为0的情况
            rangePerSegment = 1;
        }

        // 计算当前音量所在的段的索引
        int index = currentVolume / rangePerSegment;

        // 处理边界情况
        if (index < 0) {
            index = 0; // 音量值小于0时，使用第一个图片
        } else if (index >= 9) { // 如果计算出的索引超出了9（因为有9个小图片），则使用最后一个图片
            index = 8;
        }
        return index;
    }

    void logtv(String text) {
        Log.e(TAG, text);
    }

    private void showSize() {
        Log.e(TAG, "sendSize: " + sendSize);
        Log.e(TAG, "receviceSize: " + receviceSize);
    }

    @Override
    public void onKeyDown(View view) {
        Log.e("onKeyDown", "===11111111111===");
        //按键
        //01 81  +   0d 0a
        byte[] msg = null;
        switch (view.getId()) {
            case R.id.tv_mute:
                msg = new byte[]{0x01, 0x01, 0x0d, 0x0a};
                break;

            case R.id.tv_input:
                msg = new byte[]{0x01, 0x02, 0x0d, 0x0a};
                break;

            case R.id.tv_suggested_setting:
                msg = new byte[]{0x01, 0x03, 0x0d, 0x0a};
                break;

            case R.id.tv_reset:
                msg = new byte[]{0x01, 0x04, 0x0d, 0x0a};
                break;

            case R.id.tv_setting_default:
                switch (inflate.rg.getCheckedRadioButtonId()) {
                    case R.id.rb_1:
                        msg = new byte[]{0x01, 0x05, 0x0d, 0x0a};
                        break;
                    case R.id.rb_2:
                        msg = new byte[]{0x01, 0x06, 0x0d, 0x0a};
                        break;
                }
                break;
            case R.id.btn_fanxiang:
                msg = new byte[]{0x01, 0x07, 0x0d, 0x0a};
                break;
            case R.id.tv_l:
                msg = new byte[]{0x01, 0x08, 0x0d, 0x0a};
                break;
            case R.id.tv_r:
                msg = new byte[]{0x01, 0x09, 0x0d, 0x0a};
                break;
            case R.id.tv_mode1:
                msg = new byte[]{0x01, 0x0a, 0x0d, 0x0a};
                break;
            case R.id.tv_mode2:
                msg = new byte[]{0x01, 0x0b, 0x0d, 0x0a};
                break;
            case R.id.tv_mode3:
                msg = new byte[]{0x01, 0x0c, 0x0d, 0x0a};
                break;
            case R.id.tv_mode4:
                msg = new byte[]{0x01, 0x0d, 0x0d, 0x0a};
                break;
            case R.id.tv_gyzy_add:
                msg = new byte[]{0x01, 0x0e, 0x0d, 0x0a};
                break;
            case R.id.tv_gyzy_sub:
                msg = new byte[]{0x01, 0x0f, 0x0d, 0x0a};
                break;
            case R.id.tv_dyzy_add:
                msg = new byte[]{0x01, 0x10, 0x0d, 0x0a};
                break;
            case R.id.tv_dyzy_sub:
                msg = new byte[]{0x01, 0x11, 0x0d, 0x0a};
                break;
            case R.id.tv_zyzy_add:
                msg = new byte[]{0x01, 0x12, 0x0d, 0x0a};
                break;
            case R.id.tv_zyzy_sub:
                msg = new byte[]{0x01, 0x13, 0x0d, 0x0a};
                break;
            case R.id.tv_cdyzy_add:
                msg = new byte[]{0x01, 0x14, 0x0d, 0x0a};
                break;
            case R.id.tv_cdyzy_sub:
                msg = new byte[]{0x01, 0x15, 0x0d, 0x0a};
                break;
            case R.id.btn_gyyc:
                msg = new byte[]{0x01, 0x16, 0x0d, 0x0a};
                break;

        }

        if (msg != null) {
            writeData(msg);
        }
    }

    @Override
    public void onKeyContinue(View view) {
        byte[] msg = null;
        switch (view.getId()) {
            case R.id.tv_mute:
                msg = new byte[]{0x01, 0x41, 0x0d, 0x0a};
                break;

            case R.id.tv_input:
                msg = new byte[]{0x01, 0x42, 0x0d, 0x0a};
                break;

            case R.id.tv_suggested_setting:
                msg = new byte[]{0x01, 0x43, 0x0d, 0x0a};
                break;

            case R.id.tv_reset:
                msg = new byte[]{0x01, 0x44, 0x0d, 0x0a};
                break;

            case R.id.tv_setting_default:
                switch (inflate.rg.getCheckedRadioButtonId()) {
                    case R.id.rb_1:
                        msg = new byte[]{0x01, 0x45, 0x0d, 0x0a};
                        break;
                    case R.id.rb_2:
                        msg = new byte[]{0x01, 0x46, 0x0d, 0x0a};
                        break;

                }
                break;
            case R.id.btn_fanxiang:
                msg = new byte[]{0x01, 0x47, 0x0d, 0x0a};
                break;
            case R.id.tv_l:
                msg = new byte[]{0x01, 0x48, 0x0d, 0x0a};
                break;
            case R.id.tv_r:
                msg = new byte[]{0x01, 0x49, 0x0d, 0x0a};
                break;
            case R.id.tv_mode1:
                msg = new byte[]{0x01, 0x4a, 0x0d, 0x0a};
                break;
            case R.id.tv_mode2:
                msg = new byte[]{0x01, 0x4b, 0x0d, 0x0a};
                break;
            case R.id.tv_mode3:
                msg = new byte[]{0x01, 0x4c, 0x0d, 0x0a};
                break;
            case R.id.tv_mode4:
                msg = new byte[]{0x01, 0x4d, 0x0d, 0x0a};
                break;
            case R.id.tv_gyzy_add:
                msg = new byte[]{0x01, 0x4e, 0x0d, 0x0a};
                break;
            case R.id.tv_gyzy_sub:
                msg = new byte[]{0x01, 0x4f, 0x0d, 0x0a};
                break;
            case R.id.tv_dyzy_add:
                msg = new byte[]{0x01, 0x40 | 0x10, 0x0d, 0x0a};
                break;
            case R.id.tv_dyzy_sub:
                msg = new byte[]{0x01, 0x40 | 0x11, 0x0d, 0x0a};
                break;
            case R.id.tv_zyzy_add:
                msg = new byte[]{0x01, 0x40 | 0x12, 0x0d, 0x0a};
                break;
            case R.id.tv_zyzy_sub:
                msg = new byte[]{0x01, 0x40 | 0x13, 0x0d, 0x0a};
                break;
            case R.id.tv_cdyzy_add:
                msg = new byte[]{0x01, 0x40 | 0x14, 0x0d, 0x0a};
                break;
            case R.id.tv_cdyzy_sub:
                msg = new byte[]{0x01, 0x40 | 0x15, 0x0d, 0x0a};
                break;
            case R.id.btn_gyyc:
                msg = new byte[]{0x01, 0x40 | 0x16, 0x0d, 0x0a};
                break;
        }

        if (msg != null) {
            writeData(msg);
        }
    }

    @Override
    public void onKeyUp(View view) {
        Log.e("onKeyUp", "==333333333333====");
        byte[] msg = null;

        int viewId = view != null ? view.getId() : View.NO_ID;
        switch (viewId) {
            case R.id.tv_mute:
                msg = new byte[]{0x01, (byte) 0x81, 0x0d, 0x0a};
                break;

            case R.id.tv_input:
                msg = new byte[]{0x01, (byte) 0x82, 0x0d, 0x0a};
                break;

            case R.id.tv_suggested_setting:
                msg = new byte[]{0x01, (byte) 0x83, 0x0d, 0x0a};
                break;

            case R.id.tv_reset:
                msg = new byte[]{0x01, (byte) 0x84, 0x0d, 0x0a};
                break;

            case R.id.tv_setting_default:
                int checkedRadioButtonId = inflate.rg.getCheckedRadioButtonId();
                switch (checkedRadioButtonId) {
                    case R.id.rb_1:
                        msg = new byte[]{0x01, (byte) 0x85, 0x0d, 0x0a};
                        break;
                    case R.id.rb_2:
                        msg = new byte[]{0x01, (byte) 0x86, 0x0d, 0x0a};
                        break;
                }
                break;
            case R.id.btn_fanxiang:
                msg = new byte[]{0x01, (byte) 0x87, 0x0d, 0x0a};
                break;
            case R.id.tv_l:
                msg = new byte[]{0x01, (byte) 0x88, 0x0d, 0x0a};
                break;
            case R.id.tv_r:
                msg = new byte[]{0x01, (byte) 0x89, 0x0d, 0x0a};
                break;
            case R.id.tv_mode1:
                msg = new byte[]{0x01, (byte) (0x80 | 0x0a), 0x0d, 0x0a};
                break;
            case R.id.tv_mode2:
                msg = new byte[]{0x01, (byte) (0x80 | 0x0b), 0x0d, 0x0a};
                break;
            case R.id.tv_mode3:
                msg = new byte[]{0x01, (byte) (0x80 | 0x0c), 0x0d, 0x0a};
                break;
            case R.id.tv_mode4:
                msg = new byte[]{0x01, (byte) (0x80 | 0x0d), 0x0d, 0x0a};
                break;
            case R.id.tv_gyzy_add:
                msg = new byte[]{0x01, (byte) (0x80 | 0x0e), 0x0d, 0x0a};
                break;
            case R.id.tv_gyzy_sub:
                msg = new byte[]{0x01, (byte) (0x80 | 0x0f), 0x0d, 0x0a};
                break;
            case R.id.tv_dyzy_add:
                msg = new byte[]{0x01, (byte) (0x80 | 0x10), 0x0d, 0x0a};
                break;
            case R.id.tv_dyzy_sub:
                msg = new byte[]{0x01, (byte) (0x80 | 0x11), 0x0d, 0x0a};
                break;
            case R.id.tv_zyzy_add:
                msg = new byte[]{0x01, (byte) (0x80 | 0x12), 0x0d, 0x0a};
                break;
            case R.id.tv_zyzy_sub:
                msg = new byte[]{0x01, (byte) (0x80 | 0x13), 0x0d, 0x0a};
                break;
            case R.id.tv_cdyzy_add:
                msg = new byte[]{0x01, (byte) (0x80 | 0x14), 0x0d, 0x0a};
                break;
            case R.id.tv_cdyzy_sub:
                msg = new byte[]{0x01, (byte) (0x80 | 0x15), 0x0d, 0x0a};
                break;
            case R.id.btn_gyyc:
                msg = new byte[]{0x01, (byte) (0x80 | 0x16), 0x0d, 0x0a};
                break;
        }

        if (msg != null) {
            writeData(msg);
        }
    }
}
